<template>
  <a-modal
    :title="$t('technology.serial.sectionDef')"
    class="model-limit-height"
    :visible="visible"
    :width="700"
    centered
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <!--    添加区段form start-->
    <a-form-model ref="form" :model="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row :gutter="48">
        <a-col :span="12">
          <a-form-model-item
            :label="$t('technology.serial.sectionName')"
            prop="name"
            :rules="[
              {
                required: true,
                message: $t('common.emptyErr', { name: $t('technology.serial.sectionName') }),
                trigger: 'blur'
              },
              { validator: validateName }
            ]"
          >
            <s-input v-model.trim="form.name" :limit="64"></s-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item
            :label="$t('technology.serial.sectionType')"
            prop="sectionType"
            :rules="[
              {
                required: true,
                message: $t('common.emptyErr', { name: $t('technology.serial.sectionType') }),
                trigger: 'blur'
              },
              { validator: validateSectionType }
            ]"
          >
            <a-select v-model="form.sectionType" @change="handleChangeType">
              <a-select-option value="Fixed">Fixed</a-select-option>
              <a-select-option value="Param">Param</a-select-option>
              <a-select-option value="Auto">Auto</a-select-option>
              <a-select-option value="DateTime">DateTime</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0px;">{{ sectionType }}</a-divider>
      <div v-if="sectionType === 'Fixed'">
        <a-form-model-item
          :label="$t('technology.serial.textBox')"
          prop="parameter"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.textBox') }),
              trigger: 'blur'
            }
          ]"
        >
          <s-input v-model.trim="form.parameter" :limit="64"></s-input>
        </a-form-model-item>
        <a-form-model-item :label="$t('technology.serial.sectionDes')" prop="description">
          <s-textarea v-model.trim="form.description" :limit="255"></s-textarea>
        </a-form-model-item>
      </div>
      <div v-if="sectionType === 'Param'">
        <a-form-model-item
          :label="$t('technology.serial.parameter')"
          prop="parameter"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.parameter') }),
              trigger: 'blur'
            }
          ]"
        >
          <s-input v-model.trim="form.parameter"></s-input>
        </a-form-model-item>
        <a-form-model-item
          v-if="sectionType === 'Param'"
          prop="startLength"
          :label="$t('technology.serial.lengthLimit')"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.lengthLimit') }),
              trigger: 'blur'
            }
          ]"
        >
          <a-input-number
            :min="1"
            :max="totalLength"
            :step="1"
            :precision="0"
            v-model="form.startLength"
          ></a-input-number>
        </a-form-model-item>
        <a-form-model-item :label="$t('technology.serial.sectionDes')" prop="description">
          <s-textarea v-model.trim="form.description" :limit="255"></s-textarea>
        </a-form-model-item>
      </div>
      <div v-if="sectionType === 'Auto'">
        <a-form-model-item
          :label="$t('technology.serial.decimal')"
          prop="radix"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.decimal') }),
              trigger: 'change'
            }
          ]"
        >
          <a-select v-model="form.radix">
            <a-select-option value="DECIMAL">{{ $t('technology.serial.ten') }}</a-select-option>
            <a-select-option value="HEXADECIMAL">{{ $t('technology.serial.sixtee') }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="sectionType === 'Auto'"
          :label="$t('technology.serial.lengthLimit')"
          prop="startLength"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.lengthLimit') }),
              trigger: 'blur'
            }
          ]"
        >
          <a-input-number
            :max="totalLength"
            :min="1"
            :step="1"
            :precision="0"
            v-model="form.startLength"
          ></a-input-number>
        </a-form-model-item>
        <a-form-model-item
          :label="$t('technology.serial.startCode')"
          prop="startCode"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.startCode') }),
              trigger: 'blur'
            }
          ]"
        >
          <a-input-number :min="0" :step="1" :precision="0" v-model="form.startCode"></a-input-number>
        </a-form-model-item>
        <a-form-model-item
          :label="$t('technology.serial.endCode')"
          prop="endCode"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.startCode') }),
              trigger: 'blur'
            }
          ]"
        >
          <a-input-number :min="0" :step="1" :precision="0" v-model="form.endCode"></a-input-number>
        </a-form-model-item>
        <a-form-model-item
          :label="$t('technology.serial.supplyCode')"
          prop="supplyCode"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.supplyCode') }),
              trigger: 'blur'
            }
          ]"
        >
          <s-input v-model.trim="form.supplyCode"></s-input>
        </a-form-model-item>

        <!--        自动序列号重置 -->
        <a-form-model-item
          :label="$t('technology.serial.autoResetSerial')"
          prop="autoReset"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.autoResetSerial') }),
              trigger: 'change'
            }
          ]"
        >
          <a-radio-group v-model="form.autoReset">
            <a-radio :value="true">
              {{ $t('common.yes') }}
            </a-radio>
            <a-radio :value="false">
              {{ $t('common.no') }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :label="$t('technology.serial.sectionDes')" prop="description">
          <s-textarea v-model.trim="form.description" :limit="255"></s-textarea>
        </a-form-model-item>
      </div>
      <div v-if="sectionType === 'DateTime'">
        <a-form-model-item
          :label="$t('technology.serial.timeformat')"
          prop="dateType"
          :rules="[
            {
              required: true,
              message: $t('common.emptyErr', { name: $t('technology.serial.timeformat') }),
              trigger: 'change'
            }
          ]"
        >
          <a-select
            v-model="form.dateType"
            @change="
              val => {
                form.dateType = val;
              }
            "
          >
            <a-select-option value="YYYYMMDD">年月日</a-select-option>
            <a-select-option value="YYYYMM">年月</a-select-option>
            <a-select-option value="MMDDYYYY">月日年</a-select-option>
            <a-select-option value="DDMMYYYY">日月年</a-select-option>
            <a-select-option value="MMYYYY">月年</a-select-option>
            <a-select-option value="YYYYWW">年周</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :label="$t('technology.serial.sectionDes')" prop="description">
          <s-textarea v-model.trim="form.description" :limit="255"></s-textarea>
        </a-form-model-item>
      </div>
    </a-form-model>
    <!--    添加区段form end-->
  </a-modal>
</template>

<script>
import { SInput, STextarea } from '@/components';
import { asyncValidateMixin } from '@/utils/mixin';

export default {
  name: 'SectionModal',
  components: {
    SInput,
    STextarea
  },
  mixins: [asyncValidateMixin],
  data() {
    return {
      section: null,
      serialNumId: '',
      index: null,
      visible: false,
      sectionList: [],
      // form: this.$form.createForm(this),
      form: {
        serialNumId: '',
        sectionType: 'Fixed',
        name: '',
        radix: '', // 进制
        startLength: '',
        startCode: '',
        endCode: '',
        supplyCode: '', // 补充填为符
        description: '',
        dateType: '', // 时间格式
        parameter: '', // Param 的参数名
        autoReset: null
      },
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 18
        }
      },
      sectionType: 'Fixed',
      totalLength: 999999
    };
  },
  methods: {
    add(sectionList, serialNumId, totalLength) {
      this.serialNumId = serialNumId;
      this.visible = true;
      this.index = null;
      this.section = null;
      this.sectionList = sectionList;
      this.sectionType = 'Fixed';
      this.totalLength = totalLength || 999999;
    },
    edit(section, index, sectionList, totalLength) {
      this.serialNumId = section.serialNumId;
      this.section = section;
      this.index = index;
      this.visible = true;
      this.sectionList = sectionList;
      this.totalLength = totalLength || 999999;
      const {
        id,
        sectionType,
        name,
        radix,
        startLength,
        startCode,
        endCode,
        supplyCode,
        // prefixGroup,
        description,
        autoReset,
        dateType,
        parameter
      } = section;
      this.sectionType = sectionType;
      this.$nextTick(() => {
        if (sectionType === 'Auto') {
          this.form = {
            name,
            sectionType,
            radix,
            startLength,
            startCode,
            endCode,
            supplyCode,
            autoReset,
            description
          };
        } else if (sectionType === 'DateTime') {
          this.form = {
            sectionType,
            name,
            dateType,
            description
          };
        } else if (sectionType === 'Param') {
          this.form = {
            sectionType,
            name,
            parameter,
            description,
            startLength
          };
        } else {
          this.form = {
            sectionType,
            name,
            parameter,
            description
          };
        }
        this.form.id = id;
        this.form.serialNumId = this.serialNumId;
      });
    },
    handleChangeType(type) {
      this.sectionType = type;
      const { name } = this.form;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
        this.form = {
          sectionType: this.sectionType,
          name,
          radix: '', // 进制
          startLength: '',
          startCode: '',
          endCode: '',
          supplyCode: '', // 补充填为符
          description: '',
          dateType: '', // 时间格式
          parameter: '', // Param 的参数名
          autoReset: null
        };
      });
    },
    validateName(rule, value, callback) {
      const arr = this.sectionList.find((d, i) => d.name === value && i !== this.index);
      if (arr) {
        return callback('区段名称不能重复');
      }
      callback();
    },
    validateSectionType(rule, value, callback) {
      if (['Fixed', 'Param'].includes(value)) {
        return callback();
      }
      const arr = this.sectionList.find((d, i) => d.sectionType === value && i !== this.index);
      if (arr) {
        return callback(this.$t('technology.serial.repeatSectionError'));
      }
      callback();
    },
    handleSubmit() {
      const fieldNames = this.sectionField;
      const validatePromise = fieldNames.map(fieldName => {
        const p = new Promise((resolve, reject) => {
          this.$refs.form.validateField(fieldName, errorMessage => {
            if (!errorMessage) {
              resolve();
            } else {
              reject(errorMessage);
            }
          });
        });
        return p;
      });
      Promise.all(validatePromise)
        .then(() => {
          const req = {};
          for (const key of this.sectionField) {
            req[key] = this.form[key];
          }
          req.serialNumId = this.serialNumId;
          if (this.section) {
            req.id = this.section.id;
          }
          this.$emit('ok', {
            section: req,
            index: this.index
          });
          this.handleCancel();
        })
        .catch(() => {});
    },
    handleCancel() {
      this.visible = false;
      this.section = null;
      this.index = null;
      this.$refs.form.resetFields();
    }
  },
  computed: {
    sectionField() {
      if (this.sectionType === 'Fixed') {
        return ['sectionType', 'name', 'parameter', 'description'];
      }
      if (this.sectionType === 'Param') {
        return ['sectionType', 'name', 'parameter', 'description', 'startLength'];
      }
      if (this.sectionType === 'DateTime') {
        return ['sectionType', 'name', 'dateType', 'description'];
      }
      return [
        'name',
        'sectionType',
        'radix',
        'startLength',
        'startCode',
        'endCode',
        'supplyCode',
        'autoReset',
        'description'
      ];
    }
  }
};
</script>

<style scoped></style>
